<?php

namespace App\Http\Controllers\Admin;

use Illuminate\Http\Request;
use App\Http\Model\Category;
use App\Http\Model\Article;
use App\Http\Requests;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\Validator;

class ArticleController extends CommonController
{
	//get admin/article 全部文章列表
    public function index(){
        $data = Article::orderBy('art_id','desc')->paginate(10);
    	return view('admin.article.index',compact('data'));
    }
    //get admin/article/create 添加文章
    public function create(){
    	$data = (new Category)->tree();
    	return view('admin.article.add',compact('data'));
    }
    //post admin/article 添加文章提交
    public function store(){
        //添加数据数去token值
    	$input = Input::except('_token');
        //添加时间
    	$input['art_time'] = time();
        //自动验证
        $rules = [
                'art_title'=>'required',//文章标题不能为空
                'art_content'=>'required',//文章内容不能为空
            ];
            //中文提示信息
            $message = [
                'art_title.required'=>'文章标题不能为空',
                'art_content.required'=>'文章内容不能为空',
            ];
            //自动验证make方法中三个参数(验证什么信息,验证规则,中文提示信息)
            $v = Validator::make($input,$rules,$message);
            //passes()验证信息是否通过
            if($v->passes()){
                //使用create方法保存数据 需要在model中添加$guarded=[]字段 设置全部接收
                $re = Article::create($input);
                if($re){
                    return redirect('admin/article');
                }else{
                    return back()->with('errors','文章添加失败,请稍后重试!');
                }
            }else{
                //修改密码验证信息不通过 返回上一步操作 输出错误信息
                return back()->withErrors($v);
            }
    }

    //get admin/article/{article}/edit 文章编辑
    public function edit($art_id){
        $data = (new Category)->tree();
        $field = Article::find($art_id);
        return view('admin.article.edit',compact('data','field'));
    }

    //put admin/article/{article}   文章的修改更新
    public function update($art_id){
        $input = Input::except('_token','_method');
        $re = Article::where('art_id',$art_id)->update($input);
        if($re){
            return redirect('admin/article');
        }else{
            return back()->with('errors','文章更新失败,请稍后重试!');
        }
    }

    //delete admin/article/{article} 删除单个文章
    public function destroy($art_id){
        //查询要删除的数据 根据id查询
        $re = Article::where('art_id',$art_id)->delete();
        //数据删除成功
        if($re){
            //数据删除成功 修改状态 输出信息
            $data = [
                'status' => 0,
                'msg' => '文章删除成功！',
            ];
        }else{
            //数据删除失败 修改状态 输出信息
            $data = [
                'status' => 1,
                'msg' => '文章删除失败，请稍后重试！',
            ];
        }
        return $data;
    } 
}
